
#include "controller.h"
#include <fstream>
#include <event/events.h>

Controller::Controller(){
  dm.indexDirectory(".");
  L = NULL;
  stage = NULL;
  newStage();
}

Controller::~Controller(){
  if(L) lua_close(L);
}

void Controller::_clean(){
  if(L) lua_close(L);
  if(stage) delete stage;
  L = luaL_newstate();
  luaL_openlibs(L);
  stage = new Stage;
}

int Controller::newStage(){
  events::Fire(new events::PrintConsole("Creating new stage"));
  _clean();
  return 0;
}

int Controller::loadStage(std::string name){
  char temp[128];

  _clean();

  sprintf(temp, "Loading %s", name.c_str());
  events::Fire(new events::PrintConsole(temp));

  char * data = NULL;
  int size = dm.load(name, &data);
  if(size < 0) return -1;
  if(luaL_loadbuffer(L, data, size, "stage")) return -2;
  if(lua_pcall(L, 0, 0, 0)) return -3;

  lua_getfield(L, LUA_GLOBALSINDEX, "stage");

  lua_getfield(L, -1, "room");
  stage->rooms.resize(lua_objlen(L, -1));
  for(int i = 0; i < stage->rooms.size(); i++) {
    lua_pushinteger(L, i+1);
    lua_gettable(L, -2);
    lua_getfield(L, -1, "x");
    stage->rooms[i].origin_x = lua_tointeger(L, -1);
    lua_pop(L, 1); //pop "x"
    lua_getfield(L, -1, "y");
    stage->rooms[i].origin_y = lua_tointeger(L, -1);
    lua_pop(L, 1); //pop "y"
    lua_getfield(L, -1, "width");
    stage->rooms[i].width = lua_tointeger(L, -1);
    lua_pop(L, 1); //pop "width"
    lua_getfield(L, -1, "height");
    stage->rooms[i].height = lua_tointeger(L, -1);
    lua_pop(L, 1); //pop "height"
    lua_pop(L, 1); //pop table
  }
  lua_pop(L, 1); //pop "room"

  lua_pop(L, 1); //pop "stage"

  sprintf(temp, "Rooms: %d", stage->rooms.size());
  events::Fire(new events::PrintConsole(temp));

  delete data;
  return 0;
}

int Controller::saveStageToFile(std::string filename){
  std::ofstream file_out;
  file_out.open(filename.c_str());
  file_out<<"stage = {\n\n";

  file_out<<"  room = {\n";
  for(int i = 0; i < stage->rooms.size(); i++){
    Room * r = &(stage->rooms[i]);
    file_out<<"    {x="<<r->origin_x<<",y="<<r->origin_y<<",width="<<r->width<<",height="<<r->height<<"},\n";
  }
  file_out<<"  }\n\n";
  file_out<<"}\n";
  file_out.close();
  dm.addIndex(filename, filename);
  return 0;
}


